package com.doliere.android.app.p2p.listeners;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import com.doliere.android.app.p2p.services.P2pService;

import android.annotation.SuppressLint;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager.DnsSdTxtRecordListener;
import android.os.AsyncTask;
	
public class P2pServiceDnsTextRecordListener {
	
	Hashtable<String, WifiP2pDevice> mSismappServiceDevices;
	Hashtable<String, String> mUserName;
	Hashtable<String, Integer> mDevicePorts;
	P2pService mService;
	
	DnsSdTxtRecordListener mListener;
	
	public P2pServiceDnsTextRecordListener(P2pService service){
		mService = service;
		mSismappServiceDevices = new Hashtable<String, WifiP2pDevice>();
		mUserName = new Hashtable<String, String>();
		mDevicePorts = new Hashtable<String, Integer>();
		initializeDnsTextRecordListener();
	}
	
	public void initializeDnsTextRecordListener(){
		mListener = new DnsSdTxtRecordListener() {
			
			@SuppressLint("NewApi")
			@Override
			public void onDnsSdTxtRecordAvailable(String fulldomain,
					Map<String, String> record, WifiP2pDevice device) {
				if(mSismappServiceDevices.size() > 0 && mSismappServiceDevices.contains(device.deviceAddress)){
					mSismappServiceDevices.remove(device.deviceAddress);
				}
				mSismappServiceDevices.put(device.deviceAddress, device);
				mService.setSismappDevices(mSismappServiceDevices);
				
				if(mUserName.size() > 0 && mUserName.contains(device.deviceAddress)){
					mUserName.remove(device.deviceAddress);
				}
				mUserName.put(device.deviceAddress, record.get("USER_NAME")); // For communications sake.
				mService.setSismappUsers(mUserName);
				
				if(mDevicePorts.size() > 0 && mDevicePorts.contains(device.deviceAddress)){
					mDevicePorts.remove(device.deviceAddress);
				}
	
				try {
					mDevicePorts.put(device.deviceAddress, NumberFormat.getInstance().parse(record.get("SERVER_PORT")).intValue());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mService.setSismappDevicesPort(mDevicePorts);
			}
		};
	}
	
	public DnsSdTxtRecordListener getListener(){
		return mListener;
	}
	
	public Hashtable<String, WifiP2pDevice> getSismappServiceDevices(){
		return mSismappServiceDevices;
	}
	
	public Hashtable<String, String> getUsersName(){
		return mUserName;
	}

}
